import React, { useEffect } from "react";
import { Modal, Input, Form } from "antd";
import { actions } from "../../page/todoList/store";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";

function TableModal({ isModalVisible, addAction, updataItem, upDateAction }) {
  const [form] = Form.useForm();

  useEffect(() => {
    if (updataItem?.updata) {
      form.setFieldsValue({ ...updataItem });
    } else {
      form.resetFields();
    }
  });

  function handleCancel() {
    addAction();
    form.resetFields();
  }
  function handleOk() {
    let NewObj = form.getFieldsValue();
    if (updataItem?.updata) {
      NewObj.id = updataItem.id;
      upDateAction({ ...NewObj, updata: true, index: updataItem.index });
    } else {
      NewObj.id = Date.parse(new Date());
      addAction({ ...NewObj, upadd: true });
    }
    form.resetFields();
  }
  return (
    <div>
      <Modal
        forceRender={true}
        title="添加"
        visible={isModalVisible}
        onCancel={() => {
          handleCancel();
        }}
        onOk={() => {
          handleOk();
        }}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            label="Name"
            name="name"
            rules={[
              {
                required: true,
                message: "Please input your name",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="Address" name="address">
            <Input />
          </Form.Item>

          <Form.Item label="Age" name="age">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
export default connect(
  (state) => {
    return state;
  },
  (dispatch) => {
    return bindActionCreators(actions, dispatch);
  }
)(TableModal);
